package xin.marcher.module.diplomacy.api.impl;

import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import xin.marcher.module.common.constants.RocketDelayedLevel;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.diplomacy.api.TableDataUpdateApi;
import xin.marcher.module.diplomacy.domain.dto.TableDataChangeDTO;
import xin.marcher.module.diplomacy.manager.common.cache.FlushRedisCache;
import xin.marcher.module.diplomacy.mq.producer.DefaultProducer;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 商品信息变更服务
 */
@Slf4j
@DubboService(version = "1.0.0", interfaceClass = TableDataUpdateApi.class, retries = 0)
public class TableDataUpdateApiImpl implements TableDataUpdateApi {

    @Resource
    private FlushRedisCache flushRedisCache;

    @Resource
    private DefaultProducer defaultProducer;

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    /**
     * 商品表数据变更逆向更新缓存
     *
     * @param tableDataChangeDTO
     * @return xin.marcher.module.common.core.JsonResult
     */
    @Override
    public JsonResult tableDataChange(TableDataChangeDTO tableDataChangeDTO) {
        executorService.execute(() -> {
            try {
                flushRedisCache.flushRedisStringData(false, tableDataChangeDTO.getTableName(), Sets.newHashSet(tableDataChangeDTO.getKeyId()));
            } catch (Exception e) {
                log.error("刷新string类型缓存异常，入参为tableDataChangeDTO={}", tableDataChangeDTO, e);
            }
            try {
                flushRedisCache.flushRedisSetData(false, tableDataChangeDTO.getTableName(), Sets.newHashSet(tableDataChangeDTO.getKeyId()));
            } catch (Exception e) {
                log.error("刷新set类型缓存异常，入参为tableDataChangeDTO={}", tableDataChangeDTO, e);
            }
            try {
                flushRedisCache.flushRedisSortedSetData(false, tableDataChangeDTO.getTableName(), Sets.newHashSet(tableDataChangeDTO.getKeyId()));
            } catch (Exception e) {
                log.error("刷新sortedset类型缓存异常，入参为tableDataChangeDTO={}", tableDataChangeDTO, e);
            }
        });
        return JsonResult.buildSuccess();
    }

    @Override
    public JsonResult sendCallbackMessage(TableDataChangeDTO tableDataChangeDTO) {
        defaultProducer.sendMessage(tableDataChangeDTO.getCallbackTopic(),
                tableDataChangeDTO.getMessageNo(), RocketDelayedLevel.DELAYED_1m, "表变更消息处理完成返回延迟消息");
        return JsonResult.buildSuccess();
    }

    @Override
    public void addBloomFilter(TableDataChangeDTO tableDataChangeDTO) {
        flushRedisCache.addBloomFilter(tableDataChangeDTO);
    }
}
